import { baseUrl } from "./app.js"

const request = (url,options) => {
  uni.showLoading({
    title: '加载中'
});
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${baseUrl}${url}`,
      ...options,
      header: {
        'Content-Type': options.contentType,
        'token': uni.getStorageSync("userInfo") ? uni.getStorageSync("userInfo").token : null
      },
      success(res) {
        if (res.statusCode === 200) {
          var pages = getCurrentPages();
          if (pages.length == 8) {
            uni.showToast({
              title: "页面打开太多，将在3秒后重新返回主页面",
              icon: 'none',
              duration: 3000
            })
            setTimeout(() => {
              uni.navigateBack({
                 delta: 10
              });
            }, 3000)
            return;
          }
          if(res.data.code === 200 || res.data.code === "200") {
            resolve(res.data)
          }else if(res.data.statusCode == 400) {
            uni.showToast({
              title: res.data.message || '糟糕，出错啦',
              icon: 'none',
              duration: 3000
            })
            reject(res.data.message)
            return
          }else if(res.data.code) {
            uni.showToast({
              title: res.data.message || '糟糕，出错啦',
              icon: 'none',
              duration: 3000
            })
            reject(res.data.message)
            return
          }else {
            resolve(res.data)
          }
        } else if (res.statusCode === 401) {
          uni.showToast({
            title: res.data.message || '请重新登录',
            icon: 'none',
            duration: 3000
          })
          // uni.reLaunch({
          //   url: '/pages/login/login'
          // })
          reject(res.data.message)
        } else if (res.statusCode === 550) {
          uni.showToast({
            title: res.data.message || '糟糕，出错啦',
            icon: 'none',
            duration: 3000
          })
          reject(res.data.message)
          return
        } else if (res.statusCode === 500) {
          uni.showToast({
            title: res.data.message || '糟糕，出错啦',
            icon: 'none',
            duration: 3000
          })
          reject(res.data.message)
          return
        }
      },
      fail(error) {
        reject(error.data)
      },
      complete: () => {
        uni.hideLoading();
    }
    })
  })
}

const get = (url, options = {}) => {
  return request(url, { method: 'GET', data: options, contentType: 'application/json' })
}

const postQuery = (url, options) => {
  return request(url, { method: 'POST', data: options, contentType: 'application/x-www-form-urlencoded' })
}

const postBody = (url, options) => {
  return request(url, { method: 'POST', data: options, contentType: 'application/json' })
}

module.exports = {
  get,
  postQuery,
  postBody,
  baseUrl
}